package nb.diskfilesystem.model;

public class Disk {
    public static final int END_OF_FILE = -1;  // 文件结束标志
    private boolean[] disk;  // 模拟磁盘
    private FAT fat;

    public Disk(int totalBlocks) {
        disk = new boolean[totalBlocks];
        fat = new FileAllocationTable(totalBlocks);
        initializeDisk();  // 初始化FAT，标记前两块为已用
    }

    private void initializeDisk() {
        fat.markBlock(0);
        fat.markBlock(1);
    }

    // 坏块标记
    public void markBadBlock(int block) {
        if (isValidBlock(block)) {
            fat.markBadBlock(block);
            disk[block] = true;
        }
    }

    public int allocateBlock() {
        int block = fat.allocateBlock();
        if (block != -1) {
            disk[block] = true;  // 标记为已使用
        }
        return block;
    }

    public void freeBlock(int block) {
        if (isValidBlock(block)) {
            fat.freeBlock(block);
            disk[block] = false;  // 标记为未使用
        }
    }

    public void createFile() {
        int startBlock = allocateBlock();
        if (startBlock == -1) {
            System.out.println("磁盘空间不足，无法创建文件!");
            return;
        }

        // 模拟分配多个块
        int currentBlock = startBlock;
        while (true) {
            int nextBlock = allocateBlock();
            if (nextBlock == -1) {
                fat.setNextBlock(currentBlock, END_OF_FILE);  // 文件结束
                break;
            }
            fat.setNextBlock(currentBlock, nextBlock);
            currentBlock = nextBlock;
        }

        System.out.println("文件创建成功，起始块号：" + startBlock);
    }

    public void deleteFile(int startBlock) {
        int currentBlock = startBlock;
        while (currentBlock != FileAllocationTable.END_OF_FILE) {
            int nextBlock = fat.getNextBlock(currentBlock);
            freeBlock(currentBlock);
            currentBlock = nextBlock;
        }
        System.out.println("文件删除成功!");
    }

    public void displayFAT() {
        fat.displayFAT();
    }

    private boolean isValidBlock(int block) {
        return block >= 0 && block < disk.length;
    }

    private class FileAllocationTable extends FAT {
        public FileAllocationTable(int totalBlocks) {
            super();
        }
    }
}
